/**
 * Copyright (c) 2020 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */
package io.renren.demo.controller;

import io.renren.commons.security.user.SecurityUser;
import io.renren.commons.tools.utils.Result;
import io.renren.commons.tools.validator.ValidatorUtils;
import io.renren.commons.tools.validator.group.AddGroup;
import io.renren.commons.tools.validator.group.DefaultGroup;
import io.renren.demo.service.WorkOrderService;
import io.renren.dto.ProcessInstanceDTO;
import io.renren.dto.WorkOrderDTO;
import io.renren.service.FlowRunningService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 工单处理
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("demo/workorder")
@AllArgsConstructor
@Api(tags="工单处理")
public class WorkOrderController {
    private final WorkOrderService workOrderService;
    private final FlowRunningService flowRunningService;

    @PostMapping("start")
    @ApiOperation("启动流程")
    @PreAuthorize("hasAuthority('sys:flow:all')")
    public Result startProcess(@RequestBody WorkOrderDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        //保存表单
        dto.setSupplyName(SecurityUser.getUser().getRealName());
        workOrderService.save(dto);
        Map<String, Object> variables = new HashMap<>();
        variables.put("customerId",SecurityUser.getUser().getCustomerId());
        ProcessInstanceDTO process = flowRunningService.startProcessInstanceById(dto.getProcessDefinitionId(), dto.getId() + "", variables);
        dto.setInstanceId(process.getProcessInstanceId());
        //更新流程实例ID
        workOrderService.updateInstanceId(process.getProcessInstanceId(), dto.getId());
        return new Result();
    }

    @GetMapping("{id}")
    @ApiOperation("表单信息")
    @PreAuthorize("hasAuthority('sys:flow:all')")
    public Result<WorkOrderDTO> info(@PathVariable("id") Long id){
        WorkOrderDTO workOrderDTO = workOrderService.get(id);
        return new Result<WorkOrderDTO>().ok(workOrderDTO);
    }

}
